package com.contextor.magiccards.dao.user.personage.impl;

import com.contextor.magiccards.dao.BaseDao;
import com.contextor.magiccards.dao.user.personage.PersonageDao;
import com.contextor.magiccards.dao.utils.ShardHelper;
import com.contextor.magiccards.model.character.Personage;
import com.contextor.magiccards.model.errors.dao.ObjectNotFoundException;
import com.contextor.magiccards.model.user.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;

/**
 * User: sergey
 * Date: Mar 22, 2011 12:24:24 PM
 */
@Repository
public class PersonageDaoImpl extends BaseDao<Personage, Integer> implements PersonageDao {

    public PersonageDaoImpl() {
        super(Personage.class);
    }

    public Personage loadByUser(final User user) throws ObjectNotFoundException {
        return this.loadByUserId(ShardHelper.getShard(user.getUid()), user.getId());
    }

    public Personage loadByUserId(int shard, final String userId) throws ObjectNotFoundException {
        final Personage personage = (Personage) getHibernateTemplate().execute(new HibernateCallback<Object>() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                return session.createQuery("SELECT p FROM Personage p WHERE p.user.id = :userId")
                        .setString("userId", userId)
                        .uniqueResult();
            }
        });
        if (personage == null) {
            throw new ObjectNotFoundException("userId=" + userId);
        }
        return personage;
    }
}
